* (bug 3493) Mark edits patrolled when they are reverted
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @package MediaWiki
5 */
6
7 /**
8 * Need the CacheManager to be loaded
9 */
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.php' );
12
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
15
16 /**
17 * Class representing a MediaWiki article and history.
18 *
19 * See design.txt for an overview.
20 * Note: edit user interface and cache support functions have been
21 * moved to separate EditPage and CacheManager classes.
22 *
23 * @package MediaWiki
24 */
25 class Article {
26 /**#@+
27 * @access private
28 */
29 var $mContent, $mContentLoaded;
30 var $mUser, $mTimestamp, $mUserText;
31 var $mCounter, $mComment, $mGoodAdjustment, $mTotalAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
34 var $mId, $mTable;
35 var $mForUpdate;
36 var $mOldId;
37 var $mRevIdFetched;
38 var $mRevision;
39 /**#@-*/
40
41 /**
42 * Constructor and clear the article
43 * @param mixed &$title
44 */
45 function Article( &$title ) {
46 $this->mTitle =& $title;
47 $this->clear();
48 }
49
50 /**
51 * get the title object of the article
52 * @public
53 */
54 function getTitle() {
55 return $this->mTitle;
56 }
57
58 /**
59 * Clear the object
60 * @private
61 */
62 function clear() {
63 $this->mDataLoaded = false;
64 $this->mContentLoaded = false;
65
66 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
67 $this->mRedirectedFrom = $this->mUserText =
68 $this->mTimestamp = $this->mComment = $this->mFileCache = '';
69 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
70 $this->mTouched = '19700101000000';
71 $this->mForUpdate = false;
72 $this->mIsRedirect = false;
73 $this->mRevIdFetched = 0;
74 }
75
76 /**
77 * Note that getContent/loadContent may follow redirects if
78 * not told otherwise, and so may cause a change to mTitle.
79 *
80 * @param $noredir
81 * @return Return the text of this revision
82 */
83 function getContent( $noredir ) {
84 global $wgRequest, $wgUser, $wgOut;
85
86 # Get variables from query string :P
87 $action = $wgRequest->getText( 'action', 'view' );
88 $section = $wgRequest->getText( 'section' );
89 $preload = $wgRequest->getText( 'preload' );
90
91 $fname = 'Article::getContent';
92 wfProfileIn( $fname );
93
94 if ( 0 == $this->getID() ) {
95 if ( 'edit' == $action ) {
96 wfProfileOut( $fname );
97
98 # If requested, preload some text.
99 $text=$this->getPreloadedText($preload);
100
101 # We used to put MediaWiki:Newarticletext here if
102 # $text was empty at this point.
103 # This is now shown above the edit box instead.
104 return $text;
105 }
106 wfProfileOut( $fname );
107 $wgOut->setRobotpolicy( 'noindex,nofollow' );
108
109 $ret = wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' );
110 return "<div class='noarticletext'>$ret</div>";
111 } else {
112 $this->loadContent( $noredir );
113 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
114 if ( $this->mTitle->getNamespace() == NS_USER_TALK &&
115 $wgUser->isIP($this->mTitle->getText()) &&
116 $action=='view'
117 ) {
118 wfProfileOut( $fname );
119 return $this->mContent . "\n" .wfMsg('anontalkpagetext');
120 } else {
121 if($action=='edit') {
122 if($section!='') {
123 if($section=='new') {
124 wfProfileOut( $fname );
125 $text=$this->getPreloadedText($preload);
126 return $text;
127 }
128
129 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
130 # comments to be stripped as well)
131 $rv=$this->getSection($this->mContent,$section);
132 wfProfileOut( $fname );
133 return $rv;
134 }
135 }
136 wfProfileOut( $fname );
137 return $this->mContent;
138 }
139 }
140 }
141
142 /**
143 This function accepts a title string as parameter
144 ($preload). If this string is non-empty, it attempts
145 to fetch the current revision text. It respects
146 <includeonly>.
147 */
148 function getPreloadedText($preload) {
149 if($preload) {
150 $preloadTitle=Title::newFromText($preload);
151 if(isset($preloadTitle) && $preloadTitle->userCanRead()) {
152 $rev=Revision::newFromTitle($preloadTitle);
153 if($rev) {
154 $text=$rev->getText();
155 $text=preg_replace('/<\/?includeonly>/i','',$text);
156 return $text;
157 }
158 }
159 }
160 return '';
161 }
162
163 /**
164 * This function returns the text of a section, specified by a number ($section).
165 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
166 * the first section before any such heading (section 0).
167 *
168 * If a section contains subsections, these are also returned.
169 *
170 * @param string $text text to look in
171 * @param integer $section section number
172 * @return string text of the requested section
173 */
174 function getSection($text,$section) {
175
176 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
177 # comments to be stripped as well)
178 $striparray=array();
179 $parser=new Parser();
180 $parser->mOutputType=OT_WIKI;
181 $parser->mOptions = new ParserOptions();
182 $striptext=$parser->strip($text, $striparray, true);
183
184 # now that we can be sure that no pseudo-sections are in the source,
185 # split it up by section
186 $secs =
187 preg_split(
188 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
189 $striptext, -1,
190 PREG_SPLIT_DELIM_CAPTURE);
191 if($section==0) {
192 $rv=$secs[0];
193 } else {
194 $headline=$secs[$section*2-1];
195 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
196 $hlevel=$matches[1];
197
198 # translate wiki heading into level
199 if(strpos($hlevel,'=')!==false) {
200 $hlevel=strlen($hlevel);
201 }
202
203 $rv=$headline. $secs[$section*2];
204 $count=$section+1;
205
206 $break=false;
207 while(!empty($secs[$count*2-1]) && !$break) {
208
209 $subheadline=$secs[$count*2-1];
210 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
211 $subhlevel=$matches[1];
212 if(strpos($subhlevel,'=')!==false) {
213 $subhlevel=strlen($subhlevel);
214 }
215 if($subhlevel > $hlevel) {
216 $rv.=$subheadline.$secs[$count*2];
217 }
218 if($subhlevel <= $hlevel) {
219 $break=true;
220 }
221 $count++;
222
223 }
224 }
225 # reinsert stripped tags
226 $rv=$parser->unstrip($rv,$striparray);
227 $rv=$parser->unstripNoWiki($rv,$striparray);
228 $rv=trim($rv);
229 return $rv;
230
231 }
232
233 /**
234 * Return the oldid of the article that is to be shown.
235 * For requests with a "direction", this is not the oldid of the
236 * query
237 */
238 function getOldID() {
239 global $wgRequest, $wgOut;
240 static $lastid;
241
242 if ( isset( $lastid ) ) {
243 return $lastid;
244 }
245 # Query variables :P
246 $oldid = $wgRequest->getVal( 'oldid' );
247 if ( isset( $oldid ) ) {
248 $oldid = intval( $oldid );
249 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
250 $nextid = $this->mTitle->getNextRevisionID( $oldid );
251 if ( $nextid ) {
252 $oldid = $nextid;
253 } else {
254 $wgOut->redirect( $this->mTitle->getFullURL( 'redirect=no' ) );
255 }
256 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
257 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
258 if ( $previd ) {
259 $oldid = $previd;
260 } else {
261 # TODO
262 }
263 }
264 $lastid = $oldid;
265 }
266 return @$oldid; # "@" to be able to return "unset" without PHP complaining
267 }
268
269
270 /**
271 * Load the revision (including cur_text) into this object
272 */
273 function loadContent( $noredir = false ) {
274 global $wgOut, $wgRequest;
275
276 if ( $this->mContentLoaded ) return;
277
278 # Query variables :P
279 $oldid = $this->getOldID();
280 $redirect = $wgRequest->getVal( 'redirect' );
281
282 $fname = 'Article::loadContent';
283
284 # Pre-fill content with error message so that if something
285 # fails we'll have something telling us what we intended.
286
287 $t = $this->mTitle->getPrefixedText();
288
289 $noredir = $noredir || ($wgRequest->getVal( 'redirect' ) == 'no')
290 || $wgRequest->getCheck( 'rdfrom' );
291 $this->mOldId = $oldid;
292 $this->fetchContent( $oldid, $noredir, true );
293 }
294
295
296 /**
297 * Fetch a page record with the given conditions
298 * @param Database $dbr
299 * @param array $conditions
300 * @access private
301 */
302 function pageData( &$dbr, $conditions ) {
303 $fields = array(
304 'page_id',
305 'page_namespace',
306 'page_title',
307 'page_restrictions',
308 'page_counter',
309 'page_is_redirect',
310 'page_is_new',
311 'page_random',
312 'page_touched',
313 'page_latest',
314 'page_len' ) ;
315 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
316 $row = $dbr->selectRow( 'page',
317 $fields,
318 $conditions,
319 'Article::pageData' );
320 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
321 return $row ;
322 }
323
324 function pageDataFromTitle( &$dbr, $title ) {
325 return $this->pageData( $dbr, array(
326 'page_namespace' => $title->getNamespace(),
327 'page_title' => $title->getDBkey() ) );
328 }
329
330 function pageDataFromId( &$dbr, $id ) {
331 return $this->pageData( $dbr, array(
332 'page_id' => intval( $id ) ) );
333 }
334
335 /**
336 * Set the general counter, title etc data loaded from
337 * some source.
338 *
339 * @param object $data
340 * @access private
341 */
342 function loadPageData( $data ) {
343 $this->mTitle->loadRestrictions( $data->page_restrictions );
344 $this->mTitle->mRestrictionsLoaded = true;
345
346 $this->mCounter = $data->page_counter;
347 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
348 $this->mIsRedirect = $data->page_is_redirect;
349 $this->mLatest = $data->page_latest;
350
351 $this->mDataLoaded = true;
352 }
353
354 /**
355 * Get text of an article from database
356 * @param int $oldid 0 for whatever the latest revision is
357 * @param bool $noredir Set to false to follow redirects
358 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
359 * @return string
360 */
361 function fetchContent( $oldid = 0, $noredir = true, $globalTitle = false ) {
362 if ( $this->mContentLoaded ) {
363 return $this->mContent;
364 }
365 $dbr =& $this->getDB();
366 $fname = 'Article::fetchContent';
367
368 # Pre-fill content with error message so that if something
369 # fails we'll have something telling us what we intended.
370 $t = $this->mTitle->getPrefixedText();
371 if( $oldid ) {
372 $t .= ',oldid='.$oldid;
373 }
374 if( isset( $redirect ) ) {
375 $redirect = ($redirect == 'no') ? 'no' : 'yes';
376 $t .= ',redirect='.$redirect;
377 }
378 $this->mContent = wfMsg( 'missingarticle', $t );
379
380 if( $oldid ) {
381 $revision = Revision::newFromId( $oldid );
382 if( is_null( $revision ) ) {
383 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
384 return false;
385 }
386 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
387 if( !$data ) {
388 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
389 return false;
390 }
391 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
392 $this->loadPageData( $data );
393 } else {
394 if( !$this->mDataLoaded ) {
395 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
396 if( !$data ) {
397 wfDebug( "$fname failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
398 return false;
399 }
400 $this->loadPageData( $data );
401 }
402 $revision = Revision::newFromId( $this->mLatest );
403 if( is_null( $revision ) ) {
404 wfDebug( "$fname failed to retrieve current page, rev_id $data->page_latest\n" );
405 return false;
406 }
407 }
408
409 # If we got a redirect, follow it (unless we've been told
410 # not to by either the function parameter or the query
411 if ( !$oldid && !$noredir ) {
412 $rt = Title::newFromRedirect( $revision->getText() );
413 # process if title object is valid and not special:userlogout
414 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL && $rt->getText() == 'Userlogout' ) ) {
415 # Gotta hand redirects to special pages differently:
416 # Fill the HTTP response "Location" header and ignore
417 # the rest of the page we're on.
418 global $wgDisableHardRedirects;
419 if( $globalTitle && !$wgDisableHardRedirects ) {
420 global $wgOut;
421 if ( $rt->getInterwiki() != '' && $rt->isLocal() ) {
422 $source = $this->mTitle->getFullURL( 'redirect=no' );
423 $wgOut->redirect( $rt->getFullURL( 'rdfrom=' . urlencode( $source ) ) ) ;
424 return false;
425 }
426 if ( $rt->getNamespace() == NS_SPECIAL ) {
427 $wgOut->redirect( $rt->getFullURL() );
428 return false;
429 }
430 }
431 if( $rt->getInterwiki() == '' ) {
432 $redirData = $this->pageDataFromTitle( $dbr, $rt );
433 if( $redirData ) {
434 $redirRev = Revision::newFromId( $redirData->page_latest );
435 if( !is_null( $redirRev ) ) {
436 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
437 $this->mTitle = $rt;
438 $data = $redirData;
439 $this->loadPageData( $data );
440 $revision = $redirRev;
441 }
442 }
443 }
444 }
445 }
446
447 # if the title's different from expected, update...
448 if( $globalTitle ) {
449 global $wgTitle;
450 if( !$this->mTitle->equals( $wgTitle ) ) {
451 $wgTitle = $this->mTitle;
452 }
453 }
454
455 # Back to the business at hand...
456 $this->mContent = $revision->getText();
457
458 $this->mUser = $revision->getUser();
459 $this->mUserText = $revision->getUserText();
460 $this->mComment = $revision->getComment();
461 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
462
463 $this->mRevIdFetched = $revision->getID();
464 $this->mContentLoaded = true;
465 $this->mRevision =& $revision;
466
467 return $this->mContent;
468 }
469
470 /**
471 * Gets the article text without using so many damn globals
472 * Returns false on error
473 *
474 * @param integer $oldid
475 */
476 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
477 return $this->fetchContent( $oldid, $noredir, false );
478 }
479
480 /**
481 * Read/write accessor to select FOR UPDATE
482 */
483 function forUpdate( $x = NULL ) {
484 return wfSetVar( $this->mForUpdate, $x );
485 }
486
487 /**
488 * Get the database which should be used for reads
489 */
490 function &getDB() {
491 $ret =& wfGetDB( DB_MASTER );
492 return $ret;
493 #if ( $this->mForUpdate ) {
494 $ret =& wfGetDB( DB_MASTER );
495 #} else {
496 # $ret =& wfGetDB( DB_SLAVE );
497 #}
498 return $ret;
499 }
500
501 /**
502 * Get options for all SELECT statements
503 * Can pass an option array, to which the class-wide options will be appended
504 */
505 function getSelectOptions( $options = '' ) {
506 if ( $this->mForUpdate ) {
507 if ( is_array( $options ) ) {
508 $options[] = 'FOR UPDATE';
509 } else {
510 $options = 'FOR UPDATE';
511 }
512 }
513 return $options;
514 }
515
516 /**
517 * Return the Article ID
518 */
519 function getID() {
520 if( $this->mTitle ) {
521 return $this->mTitle->getArticleID();
522 } else {
523 return 0;
524 }
525 }
526
527 /**
528 * Returns true if this article exists in the database.
529 * @return bool
530 */
531 function exists() {
532 return $this->getId() != 0;
533 }
534
535 /**
536 * Get the view count for this article
537 */
538 function getCount() {
539 if ( -1 == $this->mCounter ) {
540 $id = $this->getID();
541 $dbr =& $this->getDB();
542 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
543 'Article::getCount', $this->getSelectOptions() );
544 }
545 return $this->mCounter;
546 }
547
548 /**
549 * Would the given text make this article a "good" article (i.e.,
550 * suitable for including in the article count)?
551 * @param string $text Text to analyze
552 * @return integer 1 if it can be counted else 0
553 */
554 function isCountable( $text ) {
555 global $wgUseCommaCount;
556
557 if ( NS_MAIN != $this->mTitle->getNamespace() ) { return 0; }
558 if ( $this->isRedirect( $text ) ) { return 0; }
559 $token = ($wgUseCommaCount ? ',' : '[[' );
560 if ( false === strstr( $text, $token ) ) { return 0; }
561 return 1;
562 }
563
564 /**
565 * Tests if the article text represents a redirect
566 */
567 function isRedirect( $text = false ) {
568 if ( $text === false ) {
569 $this->loadContent();
570 $titleObj = Title::newFromRedirect( $this->fetchContent() );
571 } else {
572 $titleObj = Title::newFromRedirect( $text );
573 }
574 return $titleObj !== NULL;
575 }
576
577 /**
578 * Returns true if the currently-referenced revision is the current edit
579 * to this page (and it exists).
580 * @return bool
581 */
582 function isCurrent() {
583 return $this->exists() &&
584 isset( $this->mRevision ) &&
585 $this->mRevision->isCurrent();
586 }
587
588 /**
589 * Loads everything except the text
590 * This isn't necessary for all uses, so it's only done if needed.
591 * @private
592 */
593 function loadLastEdit() {
594 global $wgOut;
595
596 if ( -1 != $this->mUser )
597 return;
598
599 # New or non-existent articles have no user information
600 $id = $this->getID();
601 if ( 0 == $id ) return;
602
603 $this->mLastRevision = Revision::loadFromPageId( $this->getDB(), $id );
604 if( !is_null( $this->mLastRevision ) ) {
605 $this->mUser = $this->mLastRevision->getUser();
606 $this->mUserText = $this->mLastRevision->getUserText();
607 $this->mTimestamp = $this->mLastRevision->getTimestamp();
608 $this->mComment = $this->mLastRevision->getComment();
609 $this->mMinorEdit = $this->mLastRevision->isMinor();
610 }
611 }
612
613 function getTimestamp() {
614 $this->loadLastEdit();
615 return wfTimestamp(TS_MW, $this->mTimestamp);
616 }
617
618 function getUser() {
619 $this->loadLastEdit();
620 return $this->mUser;
621 }
622
623 function getUserText() {
624 $this->loadLastEdit();
625 return $this->mUserText;
626 }
627
628 function getComment() {
629 $this->loadLastEdit();
630 return $this->mComment;
631 }
632
633 function getMinorEdit() {
634 $this->loadLastEdit();
635 return $this->mMinorEdit;
636 }
637
638 function getRevIdFetched() {
639 $this->loadLastEdit();
640 return $this->mRevIdFetched;
641 }
642
643 function getContributors($limit = 0, $offset = 0) {
644 $fname = 'Article::getContributors';
645
646 # XXX: this is expensive; cache this info somewhere.
647
648 $title = $this->mTitle;
649 $contribs = array();
650 $dbr =& $this->getDB();
651 $revTable = $dbr->tableName( 'revision' );
652 $userTable = $dbr->tableName( 'user' );
653 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
654 $ns = $title->getNamespace();
655 $user = $this->getUser();
656 $pageId = $this->getId();
657
658 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
659 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
660 WHERE rev_page = $pageId
661 AND rev_user != $user
662 GROUP BY rev_user, rev_user_text, user_real_name
663 ORDER BY timestamp DESC";
664
665 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
666 $sql .= ' '. $this->getSelectOptions();
667
668 $res = $dbr->query($sql, $fname);
669
670 while ( $line = $dbr->fetchObject( $res ) ) {
671 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
672 }
673
674 $dbr->freeResult($res);
675 return $contribs;
676 }
677
678 /**
679 * This is the default action of the script: just view the page of
680 * the given title.
681 */
682 function view() {
683 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgContLang;
684 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
685 global $wgParserCache, $wgUseTrackbacks;
686 $sk = $wgUser->getSkin();
687
688 $fname = 'Article::view';
689 wfProfileIn( $fname );
690 # Get variables from query string
691 $oldid = $this->getOldID();
692 $diff = $wgRequest->getVal( 'diff' );
693 $rcid = $wgRequest->getVal( 'rcid' );
694 $rdfrom = $wgRequest->getVal( 'rdfrom' );
695
696 $wgOut->setArticleFlag( true );
697 $wgOut->setRobotpolicy( 'index,follow' );
698 # If we got diff and oldid in the query, we want to see a
699 # diff page instead of the article.
700
701 if ( !is_null( $diff ) ) {
702 require_once( 'DifferenceEngine.php' );
703 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
704
705 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid );
706 // DifferenceEngine directly fetched the revision:
707 $this->mRevIdFetched = $de->mNewid;
708 $de->showDiffPage();
709
710 if( $diff == 0 ) {
711 # Run view updates for current revision only
712 $this->viewUpdates();
713 }
714 wfProfileOut( $fname );
715 return;
716 }
717
718 if ( empty( $oldid ) && $this->checkTouched() ) {
719 $wgOut->setETag($wgParserCache->getETag($this, $wgUser));
720
721 if( $wgOut->checkLastModified( $this->mTouched ) ){
722 wfProfileOut( $fname );
723 return;
724 } else if ( $this->tryFileCache() ) {
725 # tell wgOut that output is taken care of
726 $wgOut->disable();
727 $this->viewUpdates();
728 wfProfileOut( $fname );
729 return;
730 }
731 }
732 # Should the parser cache be used?
733 $pcache = $wgEnableParserCache &&
734 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
735 $this->exists() &&
736 empty( $oldid );
737 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
738
739 $outputDone = false;
740 if ( $pcache ) {
741 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
742 $outputDone = true;
743 }
744 }
745 if ( !$outputDone ) {
746 $text = $this->getContent( false ); # May change mTitle by following a redirect
747
748 # Another whitelist check in case oldid or redirects are altering the title
749 if ( !$this->mTitle->userCanRead() ) {
750 $wgOut->loginToUse();
751 $wgOut->output();
752 exit;
753 }
754
755 # We're looking at an old revision
756
757 if ( !empty( $oldid ) ) {
758 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
759 $wgOut->setRobotpolicy( 'noindex,follow' );
760 }
761 $wasRedirected = false;
762 if ( '' != $this->mRedirectedFrom ) {
763 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
764 $sk = $wgUser->getSkin();
765 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, '', 'redirect=no' );
766 $s = wfMsg( 'redirectedfrom', $redir );
767 $wgOut->setSubtitle( $s );
768
769 // Check the parser cache again, for the target page
770 if( $pcache ) {
771 if( $wgOut->tryParserCache( $this, $wgUser ) ) {
772 $outputDone = true;
773 }
774 }
775 $wasRedirected = true;
776 }
777 } elseif ( !empty( $rdfrom ) ) {
778 global $wgRedirectSources;
779 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
780 $sk = $wgUser->getSkin();
781 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
782 $s = wfMsg( 'redirectedfrom', $redir );
783 $wgOut->setSubtitle( $s );
784 $wasRedirected = true;
785 }
786 }
787 }
788 if( !$outputDone ) {
789 /**
790 * @fixme: this hook doesn't work most of the time, as it doesn't
791 * trigger when the parser cache is used.
792 */
793 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
794 # wrap user css and user js in pre and don't parse
795 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
796 if (
797 $this->mTitle->getNamespace() == NS_USER &&
798 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
799 ) {
800 $wgOut->setRevisionId( $this->getRevIdFetched() );
801 $wgOut->addWikiText( wfMsg('clearyourcache'));
802 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
803 } else if ( $rt = Title::newFromRedirect( $text ) ) {
804 # Display redirect
805 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
806 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
807 if( !$wasRedirected ) {
808 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
809 }
810 $targetUrl = $rt->escapeLocalURL();
811 $titleText = htmlspecialchars( $rt->getPrefixedText() );
812 $link = $sk->makeLinkObj( $rt );
813
814 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
815 '<span class="redirectText">'.$link.'</span>' );
816
817 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
818 $catlinks = $parseout->getCategoryLinks();
819 $wgOut->addCategoryLinks($catlinks);
820 $skin = $wgUser->getSkin();
821 } else if ( $pcache ) {
822 # Display content and save to parser cache
823 $wgOut->setRevisionId( $this->getRevIdFetched() );
824 $wgOut->addPrimaryWikiText( $text, $this );
825 } else {
826 # Display content, don't attempt to save to parser cache
827
828 # Don't show section-edit links on old revisions... this way lies madness.
829 if( !$this->isCurrent() ) {
830 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
831 }
832 $wgOut->setRevisionId( $this->getRevIdFetched() );
833 $wgOut->addWikiText( $text );
834
835 if( !$this->isCurrent() ) {
836 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
837 }
838 }
839 }
840 /* title may have been set from the cache */
841 $t = $wgOut->getPageTitle();
842 if( empty( $t ) ) {
843 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
844 }
845
846 # If we have been passed an &rcid= parameter, we want to give the user a
847 # chance to mark this new article as patrolled.
848 if ( $wgUseRCPatrol
849 && !is_null($rcid)
850 && $rcid != 0
851 && $wgUser->isLoggedIn()
852 && ( $wgUser->isAllowed('patrol') || !$wgOnlySysopsCanPatrol ) )
853 {
854 $wgOut->addHTML(
855 "<div class='patrollink'>" .
856 wfMsg ( 'markaspatrolledlink',
857 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
858 ) .
859 '</div>'
860 );
861 }
862
863 # Trackbacks
864 if ($wgUseTrackbacks)
865 $this->addTrackbacks();
866
867 # Add link titles as META keywords
868 $wgOut->addMetaTags() ;
869
870 $this->viewUpdates();
871 wfProfileOut( $fname );
872 }
873
874 function addTrackbacks() {
875 global $wgOut, $wgUser;
876
877 $dbr =& wfGetDB(DB_SLAVE);
878 $tbs = $dbr->select(
879 /* FROM */ 'trackbacks',
880 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
881 /* WHERE */ array('tb_page' => $this->getID())
882 );
883
884 if (!$dbr->numrows($tbs))
885 return;
886
887 $tbtext = "";
888 while ($o = $dbr->fetchObject($tbs)) {
889 $rmvtxt = "";
890 if ($wgUser->isSysop()) {
891 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
892 . $o->tb_id . "&token=" . $wgUser->editToken());
893 $rmvtxt = wfMsg('trackbackremove', $delurl);
894 }
895 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
896 $o->tb_title,
897 $o->tb_url,
898 $o->tb_ex,
899 $o->tb_name,
900 $rmvtxt);
901 }
902 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
903 }
904
905 function deletetrackback() {
906 global $wgUser, $wgRequest, $wgOut, $wgTitle;
907
908 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
909 $wgOut->addWikitext(wfMsg('sessionfailure'));
910 return;
911 }
912
913 if ((!$wgUser->isAllowed('delete'))) {
914 $wgOut->sysopRequired();
915 return;
916 }
917
918 if (wfReadOnly()) {
919 $wgOut->readOnlyPage();
920 return;
921 }
922
923 $db =& wfGetDB(DB_MASTER);
924 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
925 $wgTitle->invalidateCache();
926 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
927 }
928
929 function render() {
930 global $wgOut;
931
932 $wgOut->setArticleBodyOnly(true);
933 $this->view();
934 }
935
936 function purge() {
937 global $wgUser, $wgRequest, $wgOut, $wgUseSquid;
938
939 if ( $wgUser->isLoggedIn() || $wgRequest->wasPosted() ) {
940 // Invalidate the cache
941 $this->mTitle->invalidateCache();
942
943 if ( $wgUseSquid ) {
944 // Commit the transaction before the purge is sent
945 $dbw = wfGetDB( DB_MASTER );
946 $dbw->immediateCommit();
947
948 // Send purge
949 $update = SquidUpdate::newSimplePurge( $this->mTitle );
950 $update->doUpdate();
951 }
952 $this->view();
953 } else {
954 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
955 $action = $this->mTitle->escapeLocalURL( 'action=purge' );
956 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
957 $msg = str_replace( '$1',
958 "<form method=\"post\" action=\"$action\">\n" .
959 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
960 "</form>\n", $msg );
961
962 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
963 $wgOut->setRobotpolicy( 'noindex,nofollow' );
964 $wgOut->addHTML( $msg );
965 }
966 }
967
968 /**
969 * Insert a new empty page record for this article.
970 * This *must* be followed up by creating a revision
971 * and running $this->updateToLatest( $rev_id );
972 * or else the record will be left in a funky state.
973 * Best if all done inside a transaction.
974 *
975 * @param Database $dbw
976 * @param string $restrictions
977 * @return int The newly created page_id key
978 * @access private
979 */
980 function insertOn( &$dbw, $restrictions = '' ) {
981 $fname = 'Article::insertOn';
982 wfProfileIn( $fname );
983
984 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
985 $dbw->insert( 'page', array(
986 'page_id' => $page_id,
987 'page_namespace' => $this->mTitle->getNamespace(),
988 'page_title' => $this->mTitle->getDBkey(),
989 'page_counter' => 0,
990 'page_restrictions' => $restrictions,
991 'page_is_redirect' => 0, # Will set this shortly...
992 'page_is_new' => 1,
993 'page_random' => wfRandom(),
994 'page_touched' => $dbw->timestamp(),
995 'page_latest' => 0, # Fill this in shortly...
996 'page_len' => 0, # Fill this in shortly...
997 ), $fname );
998 $newid = $dbw->insertId();
999
1000 $this->mTitle->resetArticleId( $newid );
1001
1002 wfProfileOut( $fname );
1003 return $newid;
1004 }
1005
1006 /**
1007 * Update the page record to point to a newly saved revision.
1008 *
1009 * @param Database $dbw
1010 * @param Revision $revision -- for ID number, and text used to set
1011 length and redirect status fields
1012 * @param int $lastRevision -- if given, will not overwrite the page field
1013 * when different from the currently set value.
1014 * Giving 0 indicates the new page flag should
1015 * be set on.
1016 * @return bool true on success, false on failure
1017 * @access private
1018 */
1019 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1020 $fname = 'Article::updateToRevision';
1021 wfProfileIn( $fname );
1022
1023 $conditions = array( 'page_id' => $this->getId() );
1024 if( !is_null( $lastRevision ) ) {
1025 # An extra check against threads stepping on each other
1026 $conditions['page_latest'] = $lastRevision;
1027 }
1028
1029 $text = $revision->getText();
1030 $dbw->update( 'page',
1031 array( /* SET */
1032 'page_latest' => $revision->getId(),
1033 'page_touched' => $dbw->timestamp(),
1034 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1035 'page_is_redirect' => Article::isRedirect( $text ) ? 1 : 0,
1036 'page_len' => strlen( $text ),
1037 ),
1038 $conditions,
1039 $fname );
1040
1041 wfProfileOut( $fname );
1042 return ( $dbw->affectedRows() != 0 );
1043 }
1044
1045 /**
1046 * If the given revision is newer than the currently set page_latest,
1047 * update the page record. Otherwise, do nothing.
1048 *
1049 * @param Database $dbw
1050 * @param Revision $revision
1051 */
1052 function updateIfNewerOn( &$dbw, $revision ) {
1053 $fname = 'Article::updateIfNewerOn';
1054 wfProfileIn( $fname );
1055
1056 $row = $dbw->selectRow(
1057 array( 'revision', 'page' ),
1058 array( 'rev_id', 'rev_timestamp' ),
1059 array(
1060 'page_id' => $this->getId(),
1061 'page_latest=rev_id' ),
1062 $fname );
1063 if( $row ) {
1064 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1065 wfProfileOut( $fname );
1066 return false;
1067 }
1068 $prev = $row->rev_id;
1069 } else {
1070 # No or missing previous revision; mark the page as new
1071 $prev = 0;
1072 }
1073
1074 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1075 wfProfileOut( $fname );
1076 return $ret;
1077 }
1078
1079 /**
1080 * Theoretically we could defer these whole insert and update
1081 * functions for after display, but that's taking a big leap
1082 * of faith, and we want to be able to report database
1083 * errors at some point.
1084 * @private
1085 */
1086 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1087 global $wgOut, $wgUser, $wgUseSquid;
1088
1089 $fname = 'Article::insertNewArticle';
1090 wfProfileIn( $fname );
1091
1092 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1093 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1094 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1095 wfProfileOut( $fname );
1096 return false;
1097 }
1098
1099 $this->mGoodAdjustment = $this->isCountable( $text );
1100 $this->mTotalAdjustment = 1;
1101
1102 $ns = $this->mTitle->getNamespace();
1103 $ttl = $this->mTitle->getDBkey();
1104
1105 # If this is a comment, add the summary as headline
1106 if($comment && $summary!="") {
1107 $text="== {$summary} ==\n\n".$text;
1108 }
1109 $text = $this->preSaveTransform( $text );
1110 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ? 1 : 0;
1111 $now = wfTimestampNow();
1112
1113 $dbw =& wfGetDB( DB_MASTER );
1114
1115 # Add the page record; stake our claim on this title!
1116 $newid = $this->insertOn( $dbw );
1117
1118 # Save the revision text...
1119 $revision = new Revision( array(
1120 'page' => $newid,
1121 'comment' => $summary,
1122 'minor_edit' => $isminor,
1123 'text' => $text
1124 ) );
1125 $revisionId = $revision->insertOn( $dbw );
1126
1127 $this->mTitle->resetArticleID( $newid );
1128
1129 # Update the page record with revision data
1130 $this->updateRevisionOn( $dbw, $revision, 0 );
1131
1132 Article::onArticleCreate( $this->mTitle );
1133 if(!$suppressRC) {
1134 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, 'default',
1135 '', strlen( $text ), $revisionId );
1136 }
1137
1138 if ($watchthis) {
1139 if(!$this->mTitle->userIsWatching()) $this->watch();
1140 } else {
1141 if ( $this->mTitle->userIsWatching() ) {
1142 $this->unwatch();
1143 }
1144 }
1145
1146 # The talk page isn't in the regular link tables, so we need to update manually:
1147 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
1148 $dbw->update( 'page',
1149 array( 'page_touched' => $dbw->timestamp($now) ),
1150 array( 'page_namespace' => $talkns,
1151 'page_title' => $ttl ),
1152 $fname );
1153
1154 # standard deferred updates
1155 $this->editUpdates( $text, $summary, $isminor, $now );
1156
1157 $oldid = 0; # new article
1158 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid, $revisionId );
1159
1160 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1161 $summary, $isminor,
1162 $watchthis, NULL ) );
1163 wfProfileOut( $fname );
1164 }
1165
1166 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1167 $this->replaceSection( $section, $text, $summary, $edittime );
1168 }
1169
1170 /**
1171 * @return string Complete article text, or null if error
1172 */
1173 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1174 $fname = 'Article::replaceSection';
1175 wfProfileIn( $fname );
1176
1177 if ($section != '') {
1178 if( is_null( $edittime ) ) {
1179 $rev = Revision::newFromTitle( $this->mTitle );
1180 } else {
1181 $dbw =& wfGetDB( DB_MASTER );
1182 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1183 }
1184 if( is_null( $rev ) ) {
1185 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1186 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1187 return null;
1188 }
1189 $oldtext = $rev->getText();
1190
1191 if($section=='new') {
1192 if($summary) $subject="== {$summary} ==\n\n";
1193 $text=$oldtext."\n\n".$subject.$text;
1194 } else {
1195
1196 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1197 # comments to be stripped as well)
1198 $striparray=array();
1199 $parser=new Parser();
1200 $parser->mOutputType=OT_WIKI;
1201 $parser->mOptions = new ParserOptions();
1202 $oldtext=$parser->strip($oldtext, $striparray, true);
1203
1204 # now that we can be sure that no pseudo-sections are in the source,
1205 # split it up
1206 # Unfortunately we can't simply do a preg_replace because that might
1207 # replace the wrong section, so we have to use the section counter instead
1208 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
1209 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
1210 $secs[$section*2]=$text."\n\n"; // replace with edited
1211
1212 # section 0 is top (intro) section
1213 if($section!=0) {
1214
1215 # headline of old section - we need to go through this section
1216 # to determine if there are any subsections that now need to
1217 # be erased, as the mother section has been replaced with
1218 # the text of all subsections.
1219 $headline=$secs[$section*2-1];
1220 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1221 $hlevel=$matches[1];
1222
1223 # determine headline level for wikimarkup headings
1224 if(strpos($hlevel,'=')!==false) {
1225 $hlevel=strlen($hlevel);
1226 }
1227
1228 $secs[$section*2-1]=''; // erase old headline
1229 $count=$section+1;
1230 $break=false;
1231 while(!empty($secs[$count*2-1]) && !$break) {
1232
1233 $subheadline=$secs[$count*2-1];
1234 preg_match(
1235 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1236 $subhlevel=$matches[1];
1237 if(strpos($subhlevel,'=')!==false) {
1238 $subhlevel=strlen($subhlevel);
1239 }
1240 if($subhlevel > $hlevel) {
1241 // erase old subsections
1242 $secs[$count*2-1]='';
1243 $secs[$count*2]='';
1244 }
1245 if($subhlevel <= $hlevel) {
1246 $break=true;
1247 }
1248 $count++;
1249
1250 }
1251
1252 }
1253 $text=join('',$secs);
1254 # reinsert the stuff that we stripped out earlier
1255 $text=$parser->unstrip($text,$striparray);
1256 $text=$parser->unstripNoWiki($text,$striparray);
1257 }
1258
1259 }
1260 wfProfileOut( $fname );
1261 return $text;
1262 }
1263
1264 /**
1265 * Change an existing article. Puts the previous version back into the old table, updates RC
1266 * and all necessary caches, mostly via the deferred update array.
1267 *
1268 * It is possible to call this function from a command-line script, but note that you should
1269 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1270 */
1271 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1272 global $wgOut, $wgUser, $wgDBtransactions, $wgMwRedir, $wgUseSquid;
1273 global $wgPostCommitUpdateList, $wgUseFileCache;
1274
1275 $fname = 'Article::updateArticle';
1276 wfProfileIn( $fname );
1277 $good = true;
1278
1279 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1280 &$summary, &$minor,
1281 &$watchthis, &$sectionanchor ) ) ) {
1282 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1283 wfProfileOut( $fname );
1284 return false;
1285 }
1286
1287 $isminor = ( $minor && $wgUser->isLoggedIn() );
1288 if ( $this->isRedirect( $text ) ) {
1289 # Remove all content but redirect
1290 # This could be done by reconstructing the redirect from a title given by
1291 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1292 # wants to see
1293 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1294 $redir = 1;
1295 $text = $m[1] . "\n";
1296 }
1297 }
1298 else { $redir = 0; }
1299
1300 $text = $this->preSaveTransform( $text );
1301 $dbw =& wfGetDB( DB_MASTER );
1302 $now = wfTimestampNow();
1303
1304 # Update article, but only if changed.
1305
1306 # It's important that we either rollback or complete, otherwise an attacker could
1307 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1308 # could conceivably have the same effect, especially if cur is locked for long periods.
1309 if( !$wgDBtransactions ) {
1310 $userAbort = ignore_user_abort( true );
1311 }
1312
1313 $oldtext = $this->getContent( true );
1314 $oldsize = strlen( $oldtext );
1315 $newsize = strlen( $text );
1316 $lastRevision = 0;
1317 $revisionId = 0;
1318
1319 if ( 0 != strcmp( $text, $oldtext ) ) {
1320 $this->mGoodAdjustment = $this->isCountable( $text )
1321 - $this->isCountable( $oldtext );
1322 $this->mTotalAdjustment = 0;
1323 $now = wfTimestampNow();
1324
1325 $lastRevision = $dbw->selectField(
1326 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1327
1328 $revision = new Revision( array(
1329 'page' => $this->getId(),
1330 'comment' => $summary,
1331 'minor_edit' => $isminor,
1332 'text' => $text
1333 ) );
1334
1335 $dbw->immediateCommit();
1336 $dbw->begin();
1337 $revisionId = $revision->insertOn( $dbw );
1338
1339 # Update page
1340 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1341
1342 if( !$ok ) {
1343 /* Belated edit conflict! Run away!! */
1344 $good = false;
1345 $dbw->rollback();
1346 } else {
1347 # Update recentchanges and purge cache and whatnot
1348 $bot = (int)($wgUser->isBot() || $forceBot);
1349 RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1350 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1351 $revisionId );
1352 $dbw->commit();
1353
1354 // Update caches outside the main transaction
1355 Article::onArticleEdit( $this->mTitle );
1356 }
1357 }
1358
1359 if( !$wgDBtransactions ) {
1360 ignore_user_abort( $userAbort );
1361 }
1362
1363 if ( $good ) {
1364 if ($watchthis) {
1365 if (!$this->mTitle->userIsWatching()) {
1366 $dbw->immediateCommit();
1367 $dbw->begin();
1368 $this->watch();
1369 $dbw->commit();
1370 }
1371 } else {
1372 if ( $this->mTitle->userIsWatching() ) {
1373 $dbw->immediateCommit();
1374 $dbw->begin();
1375 $this->unwatch();
1376 $dbw->commit();
1377 }
1378 }
1379 # standard deferred updates
1380 $this->editUpdates( $text, $summary, $minor, $now );
1381
1382
1383 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision, $revisionId );
1384 }
1385 wfRunHooks( 'ArticleSaveComplete',
1386 array( &$this, &$wgUser, $text,
1387 $summary, $minor,
1388 $watchthis, $sectionanchor ) );
1389 wfProfileOut( $fname );
1390 return $good;
1391 }
1392
1393 /**
1394 * After we've either updated or inserted the article, update
1395 * the link tables and redirect to the new page.
1396 */
1397 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid, $newid ) {
1398 global $wgUseDumbLinkUpdate, $wgAntiLockFlags, $wgOut, $wgUser, $wgLinkCache;
1399 global $wgUseEnotif;
1400
1401 $fname = 'Article::showArticle';
1402 wfProfileIn( $fname );
1403
1404 $wgLinkCache = new LinkCache();
1405
1406 if ( !$wgUseDumbLinkUpdate ) {
1407 # Preload links to reduce lock time
1408 if ( $wgAntiLockFlags & ALF_PRELOAD_LINKS ) {
1409 $wgLinkCache->preFill( $this->mTitle );
1410 $wgLinkCache->clear();
1411 }
1412 }
1413
1414 # Parse the text and save it to the parser cache
1415 $wgOut = new OutputPage();
1416 $wgOut->setParserOptions( ParserOptions::newFromUser( $wgUser ) );
1417 $wgOut->setRevisionId( $newid );
1418 $wgOut->addPrimaryWikiText( $text, $this );
1419
1420 if ( !$wgUseDumbLinkUpdate ) {
1421 # Move the current links back to the second register
1422 $wgLinkCache->swapRegisters();
1423
1424 # Get old version of link table to allow incremental link updates
1425 # Lock this data now since it is needed for an update
1426 $wgLinkCache->forUpdate( true );
1427 $wgLinkCache->preFill( $this->mTitle );
1428
1429 # Swap this old version back into its rightful place
1430 $wgLinkCache->swapRegisters();
1431 }
1432
1433 if( $this->isRedirect( $text ) )
1434 $r = 'redirect=no';
1435 else
1436 $r = '';
1437 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1438
1439 wfProfileOut( $fname );
1440 }
1441
1442 /**
1443 * Mark this particular edit as patrolled
1444 */
1445 function markpatrolled() {
1446 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1447 $wgOut->setRobotpolicy( 'noindex,follow' );
1448
1449 if ( !$wgUseRCPatrol )
1450 {
1451 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1452 return;
1453 }
1454 if ( $wgUser->isAnon() )
1455 {
1456 $wgOut->loginToUse();
1457 return;
1458 }
1459 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1460 {
1461 $wgOut->sysopRequired();
1462 return;
1463 }
1464 $rcid = $wgRequest->getVal( 'rcid' );
1465 if ( !is_null ( $rcid ) )
1466 {
1467 RecentChange::markPatrolled( $rcid );
1468 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1469 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1470
1471 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1472 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1473 }
1474 else
1475 {
1476 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1477 }
1478 }
1479
1480 /**
1481 * Validate function
1482 */
1483 function validate() {
1484 global $wgOut, $wgUser, $wgRequest, $wgUseValidation;
1485
1486 if ( !$wgUseValidation ) # Are we using article validation at all?
1487 {
1488 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1489 return ;
1490 }
1491
1492 $wgOut->setRobotpolicy( 'noindex,follow' );
1493 $revision = $wgRequest->getVal( 'revision' );
1494
1495 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1496
1497 $v = new Validation ;
1498 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1499 $t = $v->showList ( $this ) ;
1500 else if ( $wgRequest->getVal ( "mode" , "" ) == "details" )
1501 $t = $v->showDetails ( $this , $wgRequest->getVal( 'revision' ) ) ;
1502 else
1503 $t = $v->validatePageForm ( $this , $revision ) ;
1504
1505 $wgOut->addHTML ( $t ) ;
1506 }
1507
1508 /**
1509 * Add this page to $wgUser's watchlist
1510 */
1511
1512 function watch() {
1513
1514 global $wgUser, $wgOut;
1515
1516 if ( $wgUser->isAnon() ) {
1517 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1518 return;
1519 }
1520 if ( wfReadOnly() ) {
1521 $wgOut->readOnlyPage();
1522 return;
1523 }
1524
1525 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1526
1527 $wgUser->addWatch( $this->mTitle );
1528 $wgUser->saveSettings();
1529
1530 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1531
1532 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1533 $wgOut->setRobotpolicy( 'noindex,follow' );
1534
1535 $link = $this->mTitle->getPrefixedText();
1536 $text = wfMsg( 'addedwatchtext', $link );
1537 $wgOut->addWikiText( $text );
1538 }
1539
1540 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1541 }
1542
1543 /**
1544 * Stop watching a page
1545 */
1546
1547 function unwatch() {
1548
1549 global $wgUser, $wgOut;
1550
1551 if ( $wgUser->isAnon() ) {
1552 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1553 return;
1554 }
1555 if ( wfReadOnly() ) {
1556 $wgOut->readOnlyPage();
1557 return;
1558 }
1559
1560 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1561
1562 $wgUser->removeWatch( $this->mTitle );
1563 $wgUser->saveSettings();
1564
1565 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1566
1567 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1568 $wgOut->setRobotpolicy( 'noindex,follow' );
1569
1570 $link = $this->mTitle->getPrefixedText();
1571 $text = wfMsg( 'removedwatchtext', $link );
1572 $wgOut->addWikiText( $text );
1573 }
1574
1575 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1576 }
1577
1578 /**
1579 * protect a page
1580 */
1581 function protect( $limit = 'sysop' ) {
1582 global $wgUser, $wgOut, $wgRequest;
1583
1584 if ( ! $wgUser->isAllowed('protect') ) {
1585 $wgOut->sysopRequired();
1586 return;
1587 }
1588
1589 // bug 2261
1590 if ( $this->mTitle->isProtected() && $limit == 'sysop' ) {
1591 $this->view();
1592 return;
1593 }
1594
1595 if ( wfReadOnly() ) {
1596 $wgOut->readOnlyPage();
1597 return;
1598 }
1599
1600 $id = $this->mTitle->getArticleID();
1601 if ( 0 == $id ) {
1602 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1603 return;
1604 }
1605
1606 $confirm = $wgRequest->wasPosted() &&
1607 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1608 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1609 $reason = $wgRequest->getText( 'wpReasonProtect' );
1610
1611 if ( $confirm ) {
1612 $dbw =& wfGetDB( DB_MASTER );
1613 $dbw->update( 'page',
1614 array( /* SET */
1615 'page_touched' => $dbw->timestamp(),
1616 'page_restrictions' => (string)$limit
1617 ), array( /* WHERE */
1618 'page_id' => $id
1619 ), 'Article::protect'
1620 );
1621
1622 $restrictions = "move=" . $limit;
1623 if( !$moveonly ) {
1624 $restrictions .= ":edit=" . $limit;
1625 }
1626 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1627
1628 $dbw =& wfGetDB( DB_MASTER );
1629 $dbw->update( 'page',
1630 array( /* SET */
1631 'page_touched' => $dbw->timestamp(),
1632 'page_restrictions' => $restrictions
1633 ), array( /* WHERE */
1634 'page_id' => $id
1635 ), 'Article::protect'
1636 );
1637
1638 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1639
1640 $log = new LogPage( 'protect' );
1641 if ( $limit === '' ) {
1642 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1643 } else {
1644 $log->addEntry( 'protect', $this->mTitle, $reason );
1645 }
1646 $wgOut->redirect( $this->mTitle->getFullURL() );
1647 }
1648 return;
1649 } else {
1650 return $this->confirmProtect( '', '', $limit );
1651 }
1652 }
1653
1654 /**
1655 * Output protection confirmation dialog
1656 */
1657 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1658 global $wgOut, $wgUser;
1659
1660 wfDebug( "Article::confirmProtect\n" );
1661
1662 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1663 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1664
1665 $check = '';
1666 $protcom = '';
1667 $moveonly = '';
1668
1669 if ( $limit === '' ) {
1670 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1671 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1672 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1673 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1674 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1675 } else {
1676 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1677 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1678 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1679 $moveonly = wfMsg( 'protectmoveonly' ) ; // add it using addWikiText to prevent xss. bug:3991
1680 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1681 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1682 }
1683
1684 $confirm = htmlspecialchars( wfMsg( 'protectpage' ) );
1685 $token = htmlspecialchars( $wgUser->editToken() );
1686
1687 $wgOut->addHTML( "
1688 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1689 <table border='0'>
1690 <tr>
1691 <td align='right'>
1692 <label for='wpReasonProtect'>{$protcom}:</label>
1693 </td>
1694 <td align='left'>
1695 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1696 </td>
1697 </tr>" );
1698 if($moveonly != '') {
1699 $wgOut->AddHTML( "
1700 <tr>
1701 <td align='right'>
1702 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1703 </td>
1704 <td align='left'>
1705 <label for='wpMoveOnly'> ");
1706 $wgOut->addWikiText( $moveonly ); // bug 3991
1707 $wgOut->addHTML( "
1708 </label>
1709 </td>
1710 </tr> " );
1711 }
1712 $wgOut->addHTML( "
1713 <tr>
1714 <td>&nbsp;</td>
1715 <td>
1716 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1717 </td>
1718 </tr>
1719 </table>
1720 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1721 </form>" );
1722
1723 $wgOut->returnToMain( false );
1724 }
1725
1726 /**
1727 * Unprotect the pages
1728 */
1729 function unprotect() {
1730 // bug 2261
1731 if ( $this->mTitle->isProtected() ) {
1732 return $this->protect( '' );
1733 } else {
1734 $this->view();
1735 return;
1736 }
1737 }
1738
1739 /*
1740 * UI entry point for page deletion
1741 */
1742 function delete() {
1743 global $wgUser, $wgOut, $wgRequest;
1744 $fname = 'Article::delete';
1745 $confirm = $wgRequest->wasPosted() &&
1746 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1747 $reason = $wgRequest->getText( 'wpReason' );
1748
1749 # This code desperately needs to be totally rewritten
1750
1751 # Check permissions
1752 if( ( !$wgUser->isAllowed( 'delete' ) ) ) {
1753 $wgOut->sysopRequired();
1754 return;
1755 }
1756 if( wfReadOnly() ) {
1757 $wgOut->readOnlyPage();
1758 return;
1759 }
1760
1761 # Better double-check that it hasn't been deleted yet!
1762 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1763 if( !$this->mTitle->exists() ) {
1764 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1765 return;
1766 }
1767
1768 if( $confirm ) {
1769 $this->doDelete( $reason );
1770 return;
1771 }
1772
1773 # determine whether this page has earlier revisions
1774 # and insert a warning if it does
1775 # we select the text because it might be useful below
1776 $dbr =& $this->getDB();
1777 $ns = $this->mTitle->getNamespace();
1778 $title = $this->mTitle->getDBkey();
1779 $revisions = $dbr->select( array( 'page', 'revision' ),
1780 array( 'rev_id', 'rev_user_text' ),
1781 array(
1782 'page_namespace' => $ns,
1783 'page_title' => $title,
1784 'rev_page = page_id'
1785 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1786 );
1787
1788 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1789 $skin=$wgUser->getSkin();
1790 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1791 $wgOut->addHTML( $skin->historyLink() .'</b>');
1792 }
1793
1794 # Fetch cur_text
1795 $rev = Revision::newFromTitle( $this->mTitle );
1796
1797 # Fetch name(s) of contributors
1798 $rev_name = '';
1799 $all_same_user = true;
1800 while( $row = $dbr->fetchObject( $revisions ) ) {
1801 if( $rev_name != '' && $rev_name != $row->rev_user_text ) {
1802 $all_same_user = false;
1803 } else {
1804 $rev_name = $row->rev_user_text;
1805 }
1806 }
1807
1808 if( !is_null( $rev ) ) {
1809 # if this is a mini-text, we can paste part of it into the deletion reason
1810 $text = $rev->getText();
1811
1812 #if this is empty, an earlier revision may contain "useful" text
1813 $blanked = false;
1814 if( $text == '' ) {
1815 $prev = $rev->getPrevious();
1816 if( $prev ) {
1817 $text = $prev->getText();
1818 $blanked = true;
1819 }
1820 }
1821
1822 $length = strlen( $text );
1823
1824 # this should not happen, since it is not possible to store an empty, new
1825 # page. Let's insert a standard text in case it does, though
1826 if( $length == 0 && $reason === '' ) {
1827 $reason = wfMsgForContent( 'exblank' );
1828 }
1829
1830 if( $length < 500 && $reason === '' ) {
1831 # comment field=255, let's grep the first 150 to have some user
1832 # space left
1833 global $wgContLang;
1834 $text = $wgContLang->truncate( $text, 150, '...' );
1835
1836 # let's strip out newlines
1837 $text = preg_replace( "/[\n\r]/", '', $text );
1838
1839 if( !$blanked ) {
1840 if( !$all_same_user ) {
1841 $reason = wfMsgForContent( 'excontent', $text );
1842 } else {
1843 $reason = wfMsgForContent( 'excontentauthor', $text, $rev_name );
1844 }
1845 } else {
1846 $reason = wfMsgForContent( 'exbeforeblank', $text );
1847 }
1848 }
1849 }
1850
1851 return $this->confirmDelete( '', $reason );
1852 }
1853
1854 /**
1855 * Output deletion confirmation dialog
1856 */
1857 function confirmDelete( $par, $reason ) {
1858 global $wgOut, $wgUser;
1859
1860 wfDebug( "Article::confirmDelete\n" );
1861
1862 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1863 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1864 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1865 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1866
1867 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1868
1869 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1870 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1871 $token = htmlspecialchars( $wgUser->editToken() );
1872
1873 $wgOut->addHTML( "
1874 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1875 <table border='0'>
1876 <tr>
1877 <td align='right'>
1878 <label for='wpReason'>{$delcom}:</label>
1879 </td>
1880 <td align='left'>
1881 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1882 </td>
1883 </tr>
1884 <tr>
1885 <td>&nbsp;</td>
1886 <td>
1887 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1888 </td>
1889 </tr>
1890 </table>
1891 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1892 </form>\n" );
1893
1894 $wgOut->returnToMain( false );
1895 }
1896
1897
1898 /**
1899 * Perform a deletion and output success or failure messages
1900 */
1901 function doDelete( $reason ) {
1902 global $wgOut, $wgUser, $wgContLang;
1903 $fname = 'Article::doDelete';
1904 wfDebug( $fname."\n" );
1905
1906 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1907 if ( $this->doDeleteArticle( $reason ) ) {
1908 $deleted = $this->mTitle->getPrefixedText();
1909
1910 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1911 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1912
1913 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1914 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1915
1916 $wgOut->addWikiText( $text );
1917 $wgOut->returnToMain( false );
1918 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1919 } else {
1920 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1921 }
1922 }
1923 }
1924
1925 /**
1926 * Back-end article deletion
1927 * Deletes the article with database consistency, writes logs, purges caches
1928 * Returns success
1929 */
1930 function doDeleteArticle( $reason ) {
1931 global $wgUser, $wgUseSquid, $wgDeferredUpdateList;
1932 global $wgPostCommitUpdateList, $wgUseTrackbacks;
1933
1934 $fname = 'Article::doDeleteArticle';
1935 wfDebug( $fname."\n" );
1936
1937 $dbw =& wfGetDB( DB_MASTER );
1938 $ns = $this->mTitle->getNamespace();
1939 $t = $this->mTitle->getDBkey();
1940 $id = $this->mTitle->getArticleID();
1941
1942 if ( $t == '' || $id == 0 ) {
1943 return false;
1944 }
1945
1946 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ), -1 );
1947 array_push( $wgDeferredUpdateList, $u );
1948
1949 $linksTo = $this->mTitle->getLinksTo();
1950
1951 # Squid purging
1952 if ( $wgUseSquid ) {
1953 $urls = array(
1954 $this->mTitle->getInternalURL(),
1955 $this->mTitle->getInternalURL( 'history' )
1956 );
1957
1958 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
1959 array_push( $wgPostCommitUpdateList, $u );
1960
1961 }
1962
1963 # Client and file cache invalidation
1964 Title::touchArray( $linksTo );
1965
1966
1967 // For now, shunt the revision data into the archive table.
1968 // Text is *not* removed from the text table; bulk storage
1969 // is left intact to avoid breaking block-compression or
1970 // immutable storage schemes.
1971 //
1972 // For backwards compatibility, note that some older archive
1973 // table entries will have ar_text and ar_flags fields still.
1974 //
1975 // In the future, we may keep revisions and mark them with
1976 // the rev_deleted field, which is reserved for this purpose.
1977 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1978 array(
1979 'ar_namespace' => 'page_namespace',
1980 'ar_title' => 'page_title',
1981 'ar_comment' => 'rev_comment',
1982 'ar_user' => 'rev_user',
1983 'ar_user_text' => 'rev_user_text',
1984 'ar_timestamp' => 'rev_timestamp',
1985 'ar_minor_edit' => 'rev_minor_edit',
1986 'ar_rev_id' => 'rev_id',
1987 'ar_text_id' => 'rev_text_id',
1988 ), array(
1989 'page_id' => $id,
1990 'page_id = rev_page'
1991 ), $fname
1992 );
1993
1994 # Now that it's safely backed up, delete it
1995 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1996 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1997
1998 if ($wgUseTrackbacks)
1999 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2000
2001 # Clean up recentchanges entries...
2002 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2003
2004 # Finally, clean up the link tables
2005 $t = $this->mTitle->getPrefixedDBkey();
2006
2007 Article::onArticleDelete( $this->mTitle );
2008
2009 # Delete outgoing links
2010 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2011 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2012 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2013
2014 # Log the deletion
2015 $log = new LogPage( 'delete' );
2016 $log->addEntry( 'delete', $this->mTitle, $reason );
2017
2018 # Clear the cached article id so the interface doesn't act like we exist
2019 $this->mTitle->resetArticleID( 0 );
2020 $this->mTitle->mArticleID = 0;
2021 return true;
2022 }
2023
2024 /**
2025 * Revert a modification
2026 */
2027 function rollback() {
2028 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2029 $fname = 'Article::rollback';
2030
2031 if ( ! $wgUser->isAllowed('rollback') ) {
2032 $wgOut->sysopRequired();
2033 return;
2034 }
2035 if ( wfReadOnly() ) {
2036 $wgOut->readOnlyPage( $this->getContent( true ) );
2037 return;
2038 }
2039 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2040 array( $this->mTitle->getPrefixedText(),
2041 $wgRequest->getVal( 'from' ) ) ) ) {
2042 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2043 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2044 return;
2045 }
2046 $dbw =& wfGetDB( DB_MASTER );
2047
2048 # Enhanced rollback, marks edits rc_bot=1
2049 $bot = $wgRequest->getBool( 'bot' );
2050
2051 # Replace all this user's current edits with the next one down
2052 $tt = $this->mTitle->getDBKey();
2053 $n = $this->mTitle->getNamespace();
2054
2055 # Get the last editor, lock table exclusively
2056 $dbw->begin();
2057 $current = Revision::newFromTitle( $this->mTitle );
2058 if( is_null( $current ) ) {
2059 # Something wrong... no page?
2060 $dbw->rollback();
2061 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2062 return;
2063 }
2064
2065 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2066 if( $from != $current->getUserText() ) {
2067 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2068 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2069 htmlspecialchars( $this->mTitle->getPrefixedText()),
2070 htmlspecialchars( $from ),
2071 htmlspecialchars( $current->getUserText() ) ) );
2072 if( $current->getComment() != '') {
2073 $wgOut->addHTML(
2074 wfMsg( 'editcomment',
2075 htmlspecialchars( $current->getComment() ) ) );
2076 }
2077 return;
2078 }
2079
2080 # Get the last edit not by this guy
2081 $user = intval( $current->getUser() );
2082 $user_text = $dbw->addQuotes( $current->getUserText() );
2083 $s = $dbw->selectRow( 'revision',
2084 array( 'rev_id', 'rev_timestamp' ),
2085 array(
2086 'rev_page' => $current->getPage(),
2087 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2088 ), $fname,
2089 array(
2090 'USE INDEX' => 'page_timestamp',
2091 'ORDER BY' => 'rev_timestamp DESC' )
2092 );
2093 if( $s === false ) {
2094 # Something wrong
2095 $dbw->rollback();
2096 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2097 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2098 return;
2099 }
2100
2101 $set = array();
2102 if ( $bot ) {
2103 # Mark all reverted edits as bot
2104 $set['rc_bot'] = 1;
2105 }
2106 if ( $wgUseRCPatrol ) {
2107 # Mark all reverted edits as patrolled
2108 $set['rc_patrolled'] = 1;
2109 }
2110
2111 if ( $set ) {
2112 $dbw->update( 'recentchanges', $set,
2113 array( /* WHERE */
2114 'rc_cur_id' => $current->getPage(),
2115 'rc_user_text' => $current->getUserText(),
2116 "rc_timestamp > '{$s->rev_timestamp}'",
2117 ), $fname
2118 );
2119 }
2120
2121 # Get the edit summary
2122 $target = Revision::newFromId( $s->rev_id );
2123 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2124 $newComment = $wgRequest->getText( 'summary', $newComment );
2125
2126 # Save it!
2127 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2128 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2129 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2130
2131 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2132 Article::onArticleEdit( $this->mTitle );
2133
2134 $dbw->commit();
2135 $wgOut->returnToMain( false );
2136 }
2137
2138
2139 /**
2140 * Do standard deferred updates after page view
2141 * @private
2142 */
2143 function viewUpdates() {
2144 global $wgDeferredUpdateList;
2145
2146 if ( 0 != $this->getID() ) {
2147 global $wgDisableCounters;
2148 if( !$wgDisableCounters ) {
2149 Article::incViewCount( $this->getID() );
2150 $u = new SiteStatsUpdate( 1, 0, 0 );
2151 array_push( $wgDeferredUpdateList, $u );
2152 }
2153 }
2154
2155 # Update newtalk / watchlist notification status
2156 global $wgUser;
2157 $wgUser->clearNotification( $this->mTitle );
2158 }
2159
2160 /**
2161 * Do standard deferred updates after page edit.
2162 * Every 1000th edit, prune the recent changes table.
2163 * @private
2164 * @param string $text
2165 */
2166 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
2167 global $wgDeferredUpdateList, $wgMessageCache, $wgUser;
2168
2169 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2170 wfSeedRandom();
2171 if ( 0 == mt_rand( 0, 999 ) ) {
2172 # Periodically flush old entries from the recentchanges table.
2173 global $wgRCMaxAge;
2174
2175 $dbw =& wfGetDB( DB_MASTER );
2176 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2177 $recentchanges = $dbw->tableName( 'recentchanges' );
2178 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2179 $dbw->query( $sql );
2180 }
2181 }
2182
2183 $id = $this->getID();
2184 $title = $this->mTitle->getPrefixedDBkey();
2185 $shortTitle = $this->mTitle->getDBkey();
2186
2187 if ( 0 != $id ) {
2188 $u = new LinksUpdate( $id, $title );
2189 array_push( $wgDeferredUpdateList, $u );
2190 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2191 array_push( $wgDeferredUpdateList, $u );
2192 $u = new SearchUpdate( $id, $title, $text );
2193 array_push( $wgDeferredUpdateList, $u );
2194
2195 # If this is another user's talk page, update newtalk
2196
2197 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2198 $other = User::newFromName( $shortTitle );
2199 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2200 // An anonymous user
2201 $other = new User();
2202 $other->setName( $shortTitle );
2203 }
2204 if( $other ) {
2205 $other->setNewtalk( true );
2206 }
2207 }
2208
2209 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2210 $wgMessageCache->replace( $shortTitle, $text );
2211 }
2212 }
2213 }
2214
2215 /**
2216 * @todo document this function
2217 * @private
2218 * @param string $oldid Revision ID of this article revision
2219 */
2220 function setOldSubtitle( $oldid=0 ) {
2221 global $wgLang, $wgOut, $wgUser;
2222
2223 $current = ( $oldid == $this->mLatest );
2224 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2225 $sk = $wgUser->getSkin();
2226 $lnk = $current
2227 ? wfMsg( 'currentrevisionlink' )
2228 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2229 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
2230 $nextlink = $current
2231 ? wfMsg( 'nextrevision' )
2232 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2233 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2234 $wgOut->setSubtitle( $r );
2235 }
2236
2237 /**
2238 * This function is called right before saving the wikitext,
2239 * so we can do things like signatures and links-in-context.
2240 *
2241 * @param string $text
2242 */
2243 function preSaveTransform( $text ) {
2244 global $wgParser, $wgUser;
2245 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2246 }
2247
2248 /* Caching functions */
2249
2250 /**
2251 * checkLastModified returns true if it has taken care of all
2252 * output to the client that is necessary for this request.
2253 * (that is, it has sent a cached version of the page)
2254 */
2255 function tryFileCache() {
2256 static $called = false;
2257 if( $called ) {
2258 wfDebug( " tryFileCache() -- called twice!?\n" );
2259 return;
2260 }
2261 $called = true;
2262 if($this->isFileCacheable()) {
2263 $touched = $this->mTouched;
2264 $cache = new CacheManager( $this->mTitle );
2265 if($cache->isFileCacheGood( $touched )) {
2266 global $wgOut;
2267 wfDebug( " tryFileCache() - about to load\n" );
2268 $cache->loadFromFileCache();
2269 return true;
2270 } else {
2271 wfDebug( " tryFileCache() - starting buffer\n" );
2272 ob_start( array(&$cache, 'saveToFileCache' ) );
2273 }
2274 } else {
2275 wfDebug( " tryFileCache() - not cacheable\n" );
2276 }
2277 }
2278
2279 /**
2280 * Check if the page can be cached
2281 * @return bool
2282 */
2283 function isFileCacheable() {
2284 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2285 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2286
2287 return $wgUseFileCache
2288 and (!$wgShowIPinHeader)
2289 and ($this->getID() != 0)
2290 and ($wgUser->isAnon())
2291 and (!$wgUser->getNewtalk())
2292 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2293 and (empty( $action ) || $action == 'view')
2294 and (!isset($oldid))
2295 and (!isset($diff))
2296 and (!isset($redirect))
2297 and (!isset($printable))
2298 and (!$this->mRedirectedFrom);
2299 }
2300
2301 /**
2302 * Loads cur_touched and returns a value indicating if it should be used
2303 *
2304 */
2305 function checkTouched() {
2306 $fname = 'Article::checkTouched';
2307 if( !$this->mDataLoaded ) {
2308 $dbr =& $this->getDB();
2309 $data = $this->pageDataFromId( $dbr, $this->getId() );
2310 if( $data ) {
2311 $this->loadPageData( $data );
2312 }
2313 }
2314 return !$this->mIsRedirect;
2315 }
2316
2317 /**
2318 * Edit an article without doing all that other stuff
2319 * The article must already exist; link tables etc
2320 * are not updated, caches are not flushed.
2321 *
2322 * @param string $text text submitted
2323 * @param string $comment comment submitted
2324 * @param bool $minor whereas it's a minor modification
2325 */
2326 function quickEdit( $text, $comment = '', $minor = 0 ) {
2327 $fname = 'Article::quickEdit';
2328 wfProfileIn( $fname );
2329
2330 $dbw =& wfGetDB( DB_MASTER );
2331 $dbw->begin();
2332 $revision = new Revision( array(
2333 'page' => $this->getId(),
2334 'text' => $text,
2335 'comment' => $comment,
2336 'minor_edit' => $minor ? 1 : 0,
2337 ) );
2338 $revisionId = $revision->insertOn( $dbw );
2339 $this->updateRevisionOn( $dbw, $revision );
2340 $dbw->commit();
2341
2342 wfProfileOut( $fname );
2343 }
2344
2345 /**
2346 * Used to increment the view counter
2347 *
2348 * @static
2349 * @param integer $id article id
2350 */
2351 function incViewCount( $id ) {
2352 $id = intval( $id );
2353 global $wgHitcounterUpdateFreq;
2354
2355 $dbw =& wfGetDB( DB_MASTER );
2356 $pageTable = $dbw->tableName( 'page' );
2357 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2358 $acchitsTable = $dbw->tableName( 'acchits' );
2359
2360 if( $wgHitcounterUpdateFreq <= 1 ){ //
2361 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2362 return;
2363 }
2364
2365 # Not important enough to warrant an error page in case of failure
2366 $oldignore = $dbw->ignoreErrors( true );
2367
2368 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2369
2370 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2371 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2372 # Most of the time (or on SQL errors), skip row count check
2373 $dbw->ignoreErrors( $oldignore );
2374 return;
2375 }
2376
2377 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2378 $row = $dbw->fetchObject( $res );
2379 $rown = intval( $row->n );
2380 if( $rown >= $wgHitcounterUpdateFreq ){
2381 wfProfileIn( 'Article::incViewCount-collect' );
2382 $old_user_abort = ignore_user_abort( true );
2383
2384 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2385 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2386 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2387 'GROUP BY hc_id');
2388 $dbw->query("DELETE FROM $hitcounterTable");
2389 $dbw->query('UNLOCK TABLES');
2390 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2391 'WHERE page_id = hc_id');
2392 $dbw->query("DROP TABLE $acchitsTable");
2393
2394 ignore_user_abort( $old_user_abort );
2395 wfProfileOut( 'Article::incViewCount-collect' );
2396 }
2397 $dbw->ignoreErrors( $oldignore );
2398 }
2399
2400 /**#@+
2401 * The onArticle*() functions are supposed to be a kind of hooks
2402 * which should be called whenever any of the specified actions
2403 * are done.
2404 *
2405 * This is a good place to put code to clear caches, for instance.
2406 *
2407 * This is called on page move and undelete, as well as edit
2408 * @static
2409 * @param $title_obj a title object
2410 */
2411
2412 function onArticleCreate($title_obj) {
2413 global $wgUseSquid, $wgPostCommitUpdateList;
2414
2415 $title_obj->touchLinks();
2416 $titles = $title_obj->getLinksTo();
2417
2418 # Purge squid
2419 if ( $wgUseSquid ) {
2420 $urls = $title_obj->getSquidURLs();
2421 foreach ( $titles as $linkTitle ) {
2422 $urls[] = $linkTitle->getInternalURL();
2423 }
2424 $u = new SquidUpdate( $urls );
2425 array_push( $wgPostCommitUpdateList, $u );
2426 }
2427 }
2428
2429 function onArticleDelete( $title ) {
2430 global $wgMessageCache;
2431
2432 $title->touchLinks();
2433
2434 if( $title->getNamespace() == NS_MEDIAWIKI) {
2435 $wgMessageCache->replace( $title->getDBkey(), false );
2436 }
2437 }
2438
2439 /**
2440 * Purge caches on page update etc
2441 */
2442 function onArticleEdit( $title ) {
2443 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2444
2445 $urls = array();
2446
2447 // Template namespace? Purge all articles linking here.
2448 // FIXME: When a templatelinks table arrives, use it for all includes.
2449 if ( $title->getNamespace() == NS_TEMPLATE) {
2450 $titles = $title->getLinksTo();
2451 Title::touchArray( $titles );
2452 if ( $wgUseSquid ) {
2453 foreach ( $titles as $link ) {
2454 $urls[] = $link->getInternalURL();
2455 }
2456 }
2457 }
2458
2459 # Squid updates
2460 if ( $wgUseSquid ) {
2461 $urls = array_merge( $urls, $title->getSquidURLs() );
2462 $u = new SquidUpdate( $urls );
2463 array_push( $wgPostCommitUpdateList, $u );
2464 }
2465
2466 # File cache
2467 if ( $wgUseFileCache ) {
2468 $cm = new CacheManager( $title );
2469 @unlink( $cm->fileCacheName() );
2470 }
2471 }
2472
2473 /**#@-*/
2474
2475 /**
2476 * Info about this page
2477 * Called for ?action=info when $wgAllowPageInfo is on.
2478 *
2479 * @access public
2480 */
2481 function info() {
2482 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2483 $fname = 'Article::info';
2484
2485 if ( !$wgAllowPageInfo ) {
2486 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2487 return;
2488 }
2489
2490 $page = $this->mTitle->getSubjectPage();
2491
2492 $wgOut->setPagetitle( $page->getPrefixedText() );
2493 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2494
2495 # first, see if the page exists at all.
2496 $exists = $page->getArticleId() != 0;
2497 if( !$exists ) {
2498 $wgOut->addHTML( wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2499 } else {
2500 $dbr =& $this->getDB( DB_SLAVE );
2501 $wl_clause = array(
2502 'wl_title' => $page->getDBkey(),
2503 'wl_namespace' => $page->getNamespace() );
2504 $numwatchers = $dbr->selectField(
2505 'watchlist',
2506 'COUNT(*)',
2507 $wl_clause,
2508 $fname,
2509 $this->getSelectOptions() );
2510
2511 $pageInfo = $this->pageCountInfo( $page );
2512 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2513
2514 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2515 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2516 if( $talkInfo ) {
2517 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2518 }
2519 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2520 if( $talkInfo ) {
2521 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2522 }
2523 $wgOut->addHTML( '</ul>' );
2524
2525 }
2526 }
2527
2528 /**
2529 * Return the total number of edits and number of unique editors
2530 * on a given page. If page does not exist, returns false.
2531 *
2532 * @param Title $title
2533 * @return array
2534 * @access private
2535 */
2536 function pageCountInfo( $title ) {
2537 $id = $title->getArticleId();
2538 if( $id == 0 ) {
2539 return false;
2540 }
2541
2542 $dbr =& $this->getDB( DB_SLAVE );
2543
2544 $rev_clause = array( 'rev_page' => $id );
2545 $fname = 'Article::pageCountInfo';
2546
2547 $edits = $dbr->selectField(
2548 'revision',
2549 'COUNT(rev_page)',
2550 $rev_clause,
2551 $fname,
2552 $this->getSelectOptions() );
2553
2554 $authors = $dbr->selectField(
2555 'revision',
2556 'COUNT(DISTINCT rev_user_text)',
2557 $rev_clause,
2558 $fname,
2559 $this->getSelectOptions() );
2560
2561 return array( 'edits' => $edits, 'authors' => $authors );
2562 }
2563
2564 /**
2565 * Return a list of templates used by this article.
2566 * Uses the links table to find the templates
2567 *
2568 * @return array
2569 */
2570 function getUsedTemplates() {
2571 $result = array();
2572 $id = $this->mTitle->getArticleID();
2573
2574 $db =& wfGetDB( DB_SLAVE );
2575 $res = $db->select( array( 'pagelinks' ),
2576 array( 'pl_title' ),
2577 array(
2578 'pl_from' => $id,
2579 'pl_namespace' => NS_TEMPLATE ),
2580 'Article:getUsedTemplates' );
2581 if ( false !== $res ) {
2582 if ( $db->numRows( $res ) ) {
2583 while ( $row = $db->fetchObject( $res ) ) {
2584 $result[] = $row->pl_title;
2585 }
2586 }
2587 }
2588 $db->freeResult( $res );
2589 return $result;
2590 }
2591 }
2592
2593 ?>